﻿/**
 * Copyright (c) 2013 Jeremy Wyman
 * Microsoft Public License (Ms-PL)
 * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
 * 1. Definitions
 *    The terms "reproduce", "reproduction", "derivative works", and "distribution" have the same meaning here as under U.S. copyright law.
 *    A "contribution" is the original software, or any additions or changes to the software.
 *    A "contributor" is any person that distributes its contribution under this license.
 *    "Licensed patents" are a contributor's patent claims that read directly on its contribution.
 * 2. Grant of Rights
 *    (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
 *    (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
 * 3. Conditions and Limitations
 *    (A) No Trademark License - This license does not grant you rights to use any contributors' name, logo, or trademarks.
 *    (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
 *    (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
 *    (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
 *    (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 *    
 * More info on: http://tempest.codeplex.com
**/

using System;
using System.Collections.Generic;
using System.Threading;

namespace Tempest.Collections
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <remarks>When enumerated using a foreach loop a copy of all data is made for thread-safety</remarks>
    [System.Diagnostics.DebuggerDisplay("Vector<{typeof(T)}>.Count = {Count}")]
    public sealed class Vector<T> : IList<T>
    {
        #region Contructors
        public Vector()
        {
            _isReadOnly = false;
            _list = new List<T>();
            _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        }
        public Vector(int capacity)
        {
            _isReadOnly = false;
            _list = new List<T>(capacity);
            _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        }
        public Vector(IEnumerable<T> collection)
        {
            _isReadOnly = false;
            _list = new List<T>(collection);
            _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        }
        #endregion
        #region Events
        public event Action<Vector<T>, UpdatedEventArgs<T>> Updated;
        #endregion
        #region Members
        private bool _isReadOnly;
        private List<T> _list;
        private ReaderWriterLockSlim _lock;

        public int Count { get { return _list.Count; } }
        public bool IsReadOnly { get { return _isReadOnly; } }

        public T this[int index]
        {
            get
            {
                T value;
                _lock.EnterReadLock();
                try
                {
                    if (index < 0 || index >= _list.Count)
                        throw new ArgumentOutOfRangeException("index");
                    value = _list[index];
                }
                catch { throw; }
                finally
                {
                    _lock.ExitReadLock();
                }
                return value;
            }
            set
            {
                if (_isReadOnly)
                    throw new InvalidOperationException("The Vector is read-only and cannot be ammended");
                //
                _lock.EnterReadLock();
                try
                {
                    if (index < 0 || index >= _list.Count)
                        throw new ArgumentOutOfRangeException("index");
                    _list[index] = value;
                }
                catch { throw; }
                finally
                {
                    _lock.ExitReadLock();
                }
                //
                this.OnUpdate(UpdatedEventType.ElementUpdated, value);
            }
        }
        #endregion
        #region Methods
        public void Add(T element)
        {
            if (_isReadOnly)
                throw new InvalidOperationException("The Vector is read-only and cannot be ammended");

            _lock.EnterWriteLock();
            try
            {
                _list.Add(element);
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            this.OnUpdate(UpdatedEventType.ElementAdded, element);
        }

        public void Clear()
        {
            if (_isReadOnly)
                throw new InvalidOperationException("The Vector is read-only and cannot be ammended");
            //
            T[] elements;
            //
            _lock.EnterWriteLock();
            try
            {
                elements = _list.ToArray();
                _list.Clear();
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            for (int i = 0; i < elements.Length; i++)
            {
                this.OnUpdate(UpdatedEventType.ElementRemoved, elements[i]);
            }
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array");
            if (arrayIndex < 0 || arrayIndex >= array.Length)
                throw new ArgumentOutOfRangeException("arrayIndex");
            //
            _lock.EnterReadLock();
            try
            {
                _list.CopyTo(array, arrayIndex);
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
        }

        public bool Contains(T element)
        {
            _lock.EnterReadLock();
            try
            {
                return _list.Contains(element);
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
        }

        public Vector<T> GetChainedSurrogate()
        {
            Vector<T> surrogate = new Vector<T>() { _isReadOnly = true, _list = _list, _lock = _lock };
            this.Updated += surrogate.RouteEvents;
            return surrogate;
        }

        public Vector<T> GetReadOnlyCopy()
        {
            return new Vector<T>(_list) { _isReadOnly = true };
        }

        public int IndexOf(T element)
        {
            int index = -1;
            //
            _lock.EnterReadLock();
            try
            {
                index = _list.IndexOf(element);
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
            //
            return index;
        }

        public void Insert(int index, T element)
        {
            _lock.EnterWriteLock();
            try
            {
                if (index < 0 || index > _list.Count)
                    throw new ArgumentOutOfRangeException("index");
                //
                _list.Insert(index, element);
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            this.OnUpdate(UpdatedEventType.ElementAdded, element);
        }

        public bool Remove(T element)
        {
            if (_isReadOnly)
                throw new InvalidOperationException("The Vector is read-only and cannot be ammended");
            //
            bool success = false;
            //
            _lock.EnterWriteLock();
            try
            {
                success = _list.Remove(element);               
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            this.OnUpdate(UpdatedEventType.ElementRemoved, element);
            //
            return success;
        }

        public void RemoveAt(int index)
        {
            if (_isReadOnly)
                throw new InvalidOperationException("The Vector is read-only and cannot be ammended");
            //
            T element;
            _lock.EnterWriteLock();
            try
            {
                if (index < 0 || index >= _list.Count)
                    throw new ArgumentOutOfRangeException("index");
                //
                element = _list[index];
                _list.RemoveAt(index);
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            this.OnUpdate(UpdatedEventType.ElementRemoved, element);
            //
        }

        private void RouteEvents(Vector<T> sender, UpdatedEventArgs<T> args)
        {
            if (this.Updated != null)
            {
                this.Updated(this, args);
            }
        }

        private void OnUpdate(UpdatedEventType type, T element)
        {
            if (this.Updated != null)
            {
                this.Updated(this, new UpdatedEventArgs<T>() { Element = element, Type = type });
            }
        }

        #region System.Collections.Generic.IEnumerable<T>
        public IEnumerator<T> GetEnumerator()
        {
            T[] elements = null;
            //
            _lock.EnterReadLock();
            try
            {
                elements = _list.ToArray();
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
            //
            for (int i = 0; i < elements.Length; i++)
            {
                yield return elements[i];
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            T[] elements = null;
            //
            _lock.EnterReadLock();
            try
            {
                elements = _list.ToArray();
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
            //
            for (int i = 0; i < elements.Length; i++)
            {
                yield return elements[i];
            }
        }
        #endregion
        #endregion

        public struct UpdatedEventArgs<T>
        {
            public UpdatedEventType Type;
            public T Element;
        }

        public enum UpdatedEventType
        {
            ElementAdded,
            ElementRemoved,
            ElementUpdated,
        }
    }

    
}
